﻿using DataBase;
using DataBase.Utils;
using Serilog;
using System.Linq;
using static GreenXi.App;

namespace GreenXi.ViewModel
{
    public class LoginViewModel
    {
        public enum LoginStatus { Success, Error, UsernameDoesNotExist, MultipleAccounts }

        private readonly MyDbContext _dbContext;
        private readonly Serilog.ILogger logger;

        public LoginViewModel()
        {
            _dbContext = new MyDbContext();
            logger = new LoggerConfiguration().MinimumLevel
                    .Debug()
                    .CreateLogger();
        }

        /// <summary>
        /// 登录验证（检查登录信息，并且将UserName，RoleId，RoleWeights保存在CurrentUser中）
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns>状态码</returns>
        public LoginStatus LoginCheck(string userName, string pwd)
        {
            var user = MyDbContext.Instance.Users.SingleOrDefault(x => x.IsEnabled == 1 && x.UserName == userName);
            if (user == null)
            {
                return LoginStatus.UsernameDoesNotExist;
            }

            if (user.Password == pwd)
            {
                SetCurrentUser(userName, user);
                return LoginStatus.Success;
            }
            else
            {
                return LoginStatus.Error;
            }
        }

        //保存登录账户信息
        public void SetCurrentUser(string userName, User user)
        {
            var userRole = _dbContext.UserRoleRelations.SingleOrDefault(x => x.UserId == user.UserID);
            CurrentUser.UserName = userName;
            CurrentUser.UserId = user.UserID;
            if (userRole != null)
            {
                CurrentUser.RoleId = userRole.RoleId;
                var role = _dbContext.RolePermissions.SingleOrDefault(x => x.RoleID == userRole.RoleId);

                if (role != null)
                {
                    CurrentUser.RoleLevel = role.RoleLevel;
                }
                else
                {
                    // 记录错误日志
                    logger.Information("用户权限的权重没有正确设置！");
                }
            }
            else
            {
                // 记录错误日志
                logger.Information("用户权限没有正确设置！");
            }
        }

    }
}
